# _*_ coding:utf-8 _*_
# -*- coding:utf-8 -*-

from urllib import request
import chardet
from email.mime.text import MIMEText



# 获取网页源代码
def getHtml(url):
    page = request.urlopen(url)
    html = page.read()
    return html

# 获取图片地址
def getImg(html):
    # 正则匹配
    reg = r'src="([.*\S]*\.jpg)" size="\d+" changedsize="true"'
    imgre = re.compile(reg);
    img_list = re.findall(imgre, html)

    # 返回图片地址列表
    return img_list


if __name__ == '__main__':
    # 帖子地址
    url = 'https://tieba.baidu.com/p/5775701905?red_tag=1703026724'

    # 保存图片地址的列表
    imgListSum = []

    # 遍历每一页，获取对应页面的图片地址
    for i in range(12, 24):
        # 拼接网页分页地址
        html = getHtml(url + str(i)).decode('utf-8')

        # 获取网页源代码
        imgList = getImg(html)

        # 获取图片地址并添加到列表中
        imgListSum.append(imgList)

    # 遍历下载图片
    # 按顺序自加给图片命名
    imgName = 0

    for i in imgListSum:
        for j in i:
            # 验证（打印图片地址）
            print(j)

            # 合成图片的保存路径和名字，并下载
            f = open(str(imgName) + '.jpg', 'wb')
            f.write(request.urlopen(j).read())
            f.close()

            # 命名 + 1
            imgName += 1

    # 结束标志
    print('Finish')



# url = 'https://tieba.baidu.com/p/5775701905?red_tag=1703026724'
